package com.hqs.listener.app;

import android.os.Handler;

import com.hqs.common.utils.Log;
import com.hqs.common.utils.SharedPreferenceUtil;
import com.hqs.listener.helper.DBHelper;
import com.hqs.listener.helper.Helper;
import com.hqs.listener.model.FileModel;
import com.hqs.listener.utils.FileUtil;
import com.lzy.okgo.OkGo;
import com.wenming.library.LogReport;
import com.wenming.library.save.imp.CrashWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

import io.realm.Realm;

/**
 * Created by apple on 16/9/27.
 */

public class Application extends android.app.Application {

    private static Application instance;
    
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        SharedPreferenceUtil.initSharedPreference(this);

        OkGo.getInstance().init(this);

        //        initCrashReport();
//        sendLog();

        Helper.setHandler(new Handler());

        DBHelper.init(this);
        setupDB();
    }

    private void setupDB(){
        Helper.doInBackground(new Runnable() {
            @Override
            public void run() {

                Realm realm = Realm.getDefaultInstance();
                long count = realm.where(FileModel.class).findAll().size();
                if (count < 1189){
                    try {
                        InputStream inputStream = getResources().getAssets().open("resource.txt");
                        Reader reader = new InputStreamReader(inputStream);
                        BufferedReader bufferedReader = new BufferedReader(reader);
                        ArrayList<String> files = new ArrayList<>();
                        while (true){
                            String line = bufferedReader.readLine();
                            if (line == null || line.equals("")){
                                break;
                            }
                            else{
                                files.add(line);
                            }
                        }
                        ArrayList<FileModel> fileModels = new ArrayList<>();
                        int i = 0;
                        for(String ff: files) {
                            String[] path = ff.split("/");
                            FileModel fileModel = new FileModel();
                            fileModel.fileName = path[3];
                            fileModel.path1 = path[1];
                            fileModel.path2 = path[2].substring(3);
                            fileModel.id = i;
                            fileModel.fullPath = ff;
                            fileModel.exists = true;
                            fileModel.originPath2 = path[2];
                            fileModels.add(fileModel);
                            i += 1;
                        }
                        realm.beginTransaction();
                        realm.copyToRealmOrUpdate(fileModels);
                        realm.commitTransaction();
                        realm.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public static Application getInstance() {
        return instance;
    }

    public void sendLog() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String logFile = FileUtil.logDir();
                ArrayList<File> files = FileUtil.findFiles(logFile);
                if (files != null && files.size() > 0) {
                    for (File file : files) {
                        String log = FileUtil.fileToString(file);
                        Log.print("CrashLog: " + log);

                    }
                }
                FileUtil.removeDir(new File(logFile));
            }
        }).start();

    }

    public void initCrashReport() {


        String logFile = FileUtil.logDir();
        File file = new File(logFile);
        if (file.exists()){
            file.delete();
        }
        boolean isOk = file.mkdirs();
        Log.print(isOk, logFile);

        LogReport.getInstance()
                .setCacheSize(30 * 1024 * 1024)//支持设置缓存大小，超出后清空
                .setLogDir(getApplicationContext(), logFile)
                .setWifiOnly(true)//设置只在Wifi状态下上传，设置为false为Wifi和移动网络都上传
                .setLogSaver(new CrashWriter(getApplicationContext()))//支持自定义保存崩溃信息的样式
                .init(getApplicationContext());

    }

}
